package cn.display.pixelworksx7.ui.main

import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import cn.display.pixelworksx7.R
import cn.display.pixelworksx7.adapter.RecyclerViewBaseAdapter
import cn.display.pixelworksx7.constant.GlobalData
import cn.display.pixelworksx7.databinding.AppListFragmentBinding
import cn.display.pixelworksx7.util.IrisConfigUtil
import cn.display.pixelworksx7.util.ShellUtil
import kotlin.jvm.optionals.getOrNull
import kotlin.streams.toList


class AppListFragment : Fragment() {
    private var _binding: AppListFragmentBinding? = null
    private var inflaterGlobal: LayoutInflater? = null
    private var containerGlobal: ViewGroup? = null
    private val TAG = "AppListFragment";
    var allAppList: MutableList<PackageInfo>? = mutableListOf()
    var userAppList: MutableList<PackageInfo>? = mutableListOf()
    var appListAdapter: RecyclerViewBaseAdapter? = null
    var isClickItem = false

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onStop() {
        super.onStop()
        // Log.w(tag,"onStop")
    }

    override fun onResume() {
        super.onResume()
        // Log.w(tag,"onResume")
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        if (!GlobalData.isShowSystemApp) {
            inflater.inflate(R.menu.app_list_show_system_menu, menu)
        } else {
            inflater.inflate(R.menu.app_list_hide_system_menu, menu)

        }
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val itemId = item.itemId
        when (itemId) {
            R.id.refresh_app_list -> {
                binding.searchAppName.setText(binding.searchAppName.text.toString())
                ShellUtil.toast(this.context, "刷新成功")
            }

            R.id.reset_iris_config -> {
                IrisConfigUtil.resetIrisConfigFile()
                IrisConfigUtil.loadIrisConfigFileParseToMap()
            }

            R.id.show_system_app -> {
                if (!GlobalData.isShowSystemApp) {
                    GlobalData.isShowSystemApp = true
                    item.setTitle("隐藏系统软件")
                } else {
                    GlobalData.isShowSystemApp = false
                    item.setTitle("显示系统软件")
                }
                resetAppInfoList()
                binding.searchAppName.setText(binding.searchAppName.text.toString())
                binding.searchAppName.setSelection(binding.searchAppName.text.toString().length)
            }

            else -> print("无选项")
        }
        return super.onOptionsItemSelected(item)
    }

    fun resetAppInfoList() {
        try {
            val appInfoList = context?.let { IrisConfigUtil.getAppInfoList(it.packageManager) } as MutableList
            appListAdapter?.updateItems(appInfoList)
            if (GlobalData.isShowSystemApp) {
                GlobalData.isShowSystemApp = false
                val userApplicationList =
                    context?.let { IrisConfigUtil.getAppInfoList(it.packageManager) } as MutableList
                appListAdapter?.addItems(userApplicationList)
                allAppList = appListAdapter?.packageInfoList
                GlobalData.isShowSystemApp = true
            } else {
                userAppList = appListAdapter?.packageInfoList
            }
        } catch (_: Exception) {

        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        // 未点击item&&当前fragment不可见&&试图不为空
        if (!isClickItem && !isVisibleToUser && _binding != null) {
            // 重新获取加载应用列表
            resetAppInfoList()
            // 绑定搜索栏text
            binding.searchAppName.setText(binding.searchAppName.text.toString())
            binding.searchAppName.setSelection(binding.searchAppName.text.toString().length)
            // 获取上层应用包名
            val topPackageName = ShellUtil.execCommand(
                "dumpsys activity activities|grep topResumedActivity=|tail -n 1|cut -d \"{\" -f2|cut -d \"/\" -f1|cut -d \" \" -f3",
                true
            ).successMsg
            // 当前上层应用包名不是本软件包名
            var appConfigInfo: PackageInfo?
            if (!topPackageName.equals(this.context?.packageName)) {
                // 是否展示了系统软件
                if (GlobalData.isShowSystemApp) {
                    // 从系统应用列表获取当前上层应用的ApplicationInfo
                    appConfigInfo = allAppList
                        ?.stream()?.filter { it.packageName.equals(topPackageName) }?.findFirst()?.getOrNull()
                } else {
                    // 从用户应用列表获取当前上层应用的ApplicationInfo
                    appConfigInfo = userAppList
                        ?.stream()?.filter { it.packageName.equals(topPackageName) }?.findFirst()?.getOrNull()
                }
                // 未获取到当前上层应用的ApplicationInfo
                // 说明当前上层应用是系统应用 应用列表却为展示系统应用
                if (appConfigInfo == null) {
                    // 从系统应用列表获取当前上层应用的ApplicationInfo
                    GlobalData.isShowSystemApp = true
                    val appInfoList = context?.let { IrisConfigUtil.getAppInfoList(it.packageManager) } as MutableList
                    appConfigInfo = appInfoList
                        .stream().filter { it.packageName.equals(topPackageName) }?.findFirst()?.getOrNull()
                    GlobalData.isShowSystemApp = false
                }
            } else {
                // 当前上层应用包名是本软件包名
                // 本地没有应用插帧配置
                if (GlobalData.irisConfigMap.keys.size == 0) {
                    // 通过当前应用展示的列表进行随机获取一个ApplicationInfo
                    appConfigInfo =
                        appListAdapter?.packageInfoList?.get((0..appListAdapter?.packageInfoList!!.size - 1).random())!!
                } else {
                    // 本地有应用插帧配置
                    // 本地插帧配置packageNameList
                    val irisConfigPackageNameList = GlobalData.irisConfigMap.keys.stream().toList()
                    // 从 irisConfigPackageNameList 随机获取一个元素
                    val randomPackageName =
                        irisConfigPackageNameList.get((0..irisConfigPackageNameList.size - 1).random())
                        appConfigInfo =
                            appListAdapter?.packageInfoList?.stream()
                                ?.filter({ it.packageName.equals(randomPackageName) })
                                ?.findFirst()?.getOrNull()
                }
            }
            if (appConfigInfo != null) {
                // 参数配置页面所需的插帧配置参数list
                GlobalData.params = IrisConfigUtil.getIrisConfigByPackageName(appConfigInfo.packageName)
                GlobalData.appConfigInfo = appConfigInfo
            }
        }
        if (isVisibleToUser && _binding != null) {
            // 页面可见&&视图不为空
            // 标记未点击item
            isClickItem = false
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = AppListFragmentBinding.inflate(inflater, container, false)
        inflaterGlobal = inflater
        containerGlobal = container
        val root = binding.root
        GlobalData.packageManager = this.context?.packageManager
        val appListRecyclerView: RecyclerView = binding.appListRecyclerView
        appListRecyclerView.setHasFixedSize(true)
        appListRecyclerView.layoutManager = LinearLayoutManager(context)
        appListRecyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        val appInfoList = context?.let { IrisConfigUtil.getAppInfoList(it.packageManager) }
//
        appListAdapter = appInfoList
            ?.let { RecyclerViewBaseAdapter(it) }
        appListAdapter?.setOnItemClickListener(object : RecyclerViewBaseAdapter.OnItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                if (appInfoList != null) {
                    val appConfigInfo = appInfoList.get(position)
                    GlobalData.params = IrisConfigUtil.getIrisConfigByPackageName(appConfigInfo.packageName)
                    GlobalData.appConfigInfo = appConfigInfo
                    val viewPager: ViewPager? = activity?.findViewById(R.id.view_pager)
                    if (viewPager != null) {
                        isClickItem = true
                        viewPager.currentItem = 1
                    }

                }
            }

            override fun onItemLongClick(view: View, position: Int) {
                if (appInfoList != null) {
                    ShellUtil.toast(context, appInfoList.get(position).packageName)
                }
            }
        })
        appListRecyclerView.adapter = appListAdapter
        appListRecyclerView.setHasFixedSize(true)
        val swipeRefreshLayout = this.binding.swipeRefreshLayout
        swipeRefreshLayout
            .setOnRefreshListener {
                // 在这里实现刷新操作，例如从网络获取新数据并更新 Adapter
                binding.searchAppName.setText(binding.searchAppName.text.toString())
                binding.searchAppName.setSelection(binding.searchAppName.text.toString().length)
                swipeRefreshLayout.isRefreshing = false // 刷新完成后关闭刷新动画
                ShellUtil.toast(this.context, "刷新成功")
            }
        val searchAppName = binding.searchAppName
        searchAppName.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 在此处编写只要有输入就执行的代码
                if (!s.toString().trim().equals("")) {
                    resetAppInfoList()
                    val searchApplicationList = appListAdapter?.packageInfoList?.stream()?.filter {
                        context?.let { it1 ->
                            it.applicationInfo.loadLabel(it1.packageManager).indexOf(s.toString())
                        } != -1 || it.packageName.indexOf(s.toString()) != -1
                    }?.toList()
                    if (searchApplicationList != null) {
                        appListAdapter?.updateItems(searchApplicationList)
                    }
                } else {
                    resetAppInfoList()
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun afterTextChanged(s: Editable?) {}
        })
        val topPackageName = ShellUtil.execCommand(
            "dumpsys activity activities|grep topResumedActivity=|tail -n 1|cut -d \"{\" -f2|cut -d \"/\" -f1|cut -d \" \" -f3",
            true
        ).successMsg
        if (!topPackageName.equals(this.context?.packageName)) {
            IrisConfigUtil.executeAppIrisConfig(topPackageName)
        }
        return root
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (hidden) {
            ShellUtil.toast(this.context, "离开了应用列表")
        }
    }

    companion object {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private const val ARG_SECTION_NUMBER = "section_number"

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        @JvmStatic
        fun newInstance(sectionNumber: Int): AppListFragment {
            return AppListFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_SECTION_NUMBER, sectionNumber)
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
